package org.djw.product.controller;

import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.djw.basic.exception.BusinessException;
import org.djw.basic.util.AjaxResult;
import org.djw.basic.util.LoginContext;
import org.djw.basic.util.PageList;
import org.djw.pet.domain.Pet;
import org.djw.product.domain.Product;
import org.djw.product.query.ProductQuery;
import org.djw.product.service.IProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/product")
public class ProductController {

    @Autowired
    private IProductService productService;

    @GetMapping("/{id}")
    public Product queryById(@PathVariable("id") Long id){
        return productService.loadByIdDetail(id);
    }


    /**
     * 删除
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    public AjaxResult remove(@PathVariable("id") Long id){
        try {
            productService.remove(id);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("系统繁忙,请稍后再试");
        }
    }

    @PutMapping
    public AjaxResult save(@RequestBody Product product, HttpServletRequest request){
        try {
            productService.save(product, LoginContext.getCurrentLogininfo(request));
            return AjaxResult.me();
        } catch (BusinessException e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("系统繁忙,请稍后重试!");
        }
    }

    /**
     * 分页高级查询
     * @param query
     * @return
     */
    @PostMapping
    public PageList<Product> queryPage(@RequestBody ProductQuery query){
        return productService.queryPage(query);
    }

    /**
     * 上架
     * @param ids
     * @return
     */
    @PostMapping("/onsale")
    public AjaxResult onSale(@RequestBody List<Long> ids){
        try {
            productService.onSale(ids);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("系统繁忙,请稍后再试");
        }
    }

    /**
     * 下架
     * @param ids
     * @return
     *
     * */
    @PostMapping("/offsale")
    public AjaxResult offSale(@RequestBody List<Long> ids){
        try {
            productService.offSale(ids);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("系统繁忙,请稍后再试");
        }
    }
}
